//
//  WTOSureOrderViewController.m
//  WolianwPro
//
//  Created by 李宗帅 on 17/3/2.
//  Copyright © 2017年 我连网. All rights reserved.
//

#import "WTOSureOrderViewController.h"
#import "WTOSureOrderHeadView.h"
#import "WTOSureOrderSectionHeader.h"
#import "WTOGoodsCell.h"
#import "WTOLeaveMessegeCell.h"
#import "WTOSureOrderBottomView.h"
#import "WTOPromptView.h"
#import <Masonry/Masonry.h>
//#import "WLWUserAddressViewController.h"
#import "WLWShopContactCallView.h"
#import <TKAlert&TKActionSheet/TKActionSheetController.h>
#import "ReceiveGoodsVC.h"
#import "WTOOrderPayFooterView.h"
#import "MQLHomeModelManager.h"
#import "WTOOtherExpenseCell.h"

@interface WTOSureOrderViewController ()<WTOSureOrderHeadViewDelegate,WTOSureOrderSectionDelegate,WTOSureOrderBottomViewDelegate,UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate>

@property(nonatomic,weak)UITableView *tableView;
@property(nonatomic,strong)WTOSureOrderHeadView *headView;//头部视图
@property(nonatomic,weak)WTOSureOrderBottomView *bottomView;//底部视图
@property(nonatomic,weak)WTOPromptView *promptView;//提示信息
@property(nonatomic,strong)NSMutableArray *goodsCellIndentifyArray;//商品section的cellIndentify数组
@property(nonatomic,copy)NSArray *orderGoodsArray;//商品数组

@property(nonatomic,copy)NSArray *firstSectionDataSource;//第一个section的数据源


//@property(nonatomic,strong)WTOSureOrderEntity *sureOrderEntity;//确认订单模型
//@property (nonatomic, strong) WTOAddressEntity *wtoAddressModel;//地址模型
//@property(nonatomic,strong)WTOPayModelManager *payManager;//支付模型层

#pragma mark - 提交订单参数
//@property(nonatomic,copy)NSString *jsonString;//组装的商品数组json串
//@property(nonatomic,copy)NSString *couponAmount;//代金券抵扣金额
//@property(nonatomic,copy)NSString *sid;//收货地址id
@property(nonatomic,copy)NSString *remark;//备注内容

#pragma mark - orderData(订单页面保存的数据)
@property(nonatomic,strong)NSNumber *totalAmount;//页面显示的总金额
@property(nonatomic,strong)NSNumber *disCountAmount;//抵扣金额


@property (nonatomic, strong) MQLHomeModelManager *modelManager;

// 导航栏
@property (nonatomic, assign) BOOL navTranslucent;

@property (nonatomic,assign) NSInteger orderState;//订单状态 0时已经完成  1未完成


@end

@implementation WTOSureOrderViewController

- (instancetype)initWithState:(NSInteger)state
{
    self = [super init];
    
    if (self) {
        
        self.title = @"确认订单";
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.goodsCellIndentifyArray = [[NSMutableArray alloc] init];
        _modelManager = [[MQLHomeModelManager alloc]init];
        self.orderState = state;
    }
    
    return self;
}

- (void)viewDidLoad
{
    self.title = @"确认订单";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.hidden = NO;
    
    self.isHideLeftBtn = NO;
    [super viewDidLoad];
    
    [self initSubViews];
    
    [self requestData];
    
    [self regiestNotification];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

}

-(void)regiestNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - initSubViews
-(void)initSubViews
{
    
    [self setupTableView];
    
    if (self.orderState || HDAccount.account.isAdmin) {
        
        [self initBottomView];
    }
    
}

-(void)setupTableView
{
    WTOSureOrderHeadView *headView = [[WTOSureOrderHeadView alloc] init];
    if (self.orderState) {
        headView.delegate = self;
    }
    self.tableView.tableHeaderView = headView;
    self.headView = headView;
    
    self.tableView.backgroundColor = kScrollBackGroundColor;
    [self.tableView registerClass:[WTOGoodsCell class] forCellReuseIdentifier:[WTOGoodsCell cellIndentify]];
    [self.tableView registerClass:[WTOLeaveMessegeCell class] forCellReuseIdentifier:[WTOLeaveMessegeCell cellIndentify]];
    [self.tableView registerClass:[WTOOtherExpenseCell class] forCellReuseIdentifier:[WTOOtherExpenseCell cellIndentify]];
    [self.tableView registerClass:[WTOSureOrderSectionHeader class] forHeaderFooterViewReuseIdentifier:[WTOSureOrderSectionHeader cellIdentify]];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.mas_equalTo(UIEdgeInsetsMake(64, 0, 50, 0));
    }];
    
}

-(void)initBottomView
{
    if (self.bottomView == nil) {
        
        WTOSureOrderBottomView *bottomView = [[WTOSureOrderBottomView alloc] init];
        bottomView.delegate = self;
        [self.view addSubview:bottomView];
        self.bottomView = bottomView;
        
        [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
           
            make.leading.trailing.bottom.mas_equalTo(self.view);
            make.height.mas_equalTo(@50);
            
        }];
        
    }
}

#pragma mark - PrivateMethods
-(void)requestData
{
    
    [self.headView refreshWithAddressEntity:self.modelManager.addressObj];

    
    [self refreshCellIndentifyArray];
    
    [self.tableView reloadData];
    
    //计算总金额和抵扣金额
    [self caculateTotalAmountAndDiscountAmount];
    
    if (self.orderState || HDAccount.account.isAdmin)
    {
        [self.bottomView updateWithEntityWithTotalAmount:self.totalAmount withdisCountAmount:self.disCountAmount];
    }
    
//    //请求网络数据
//    self.jsonString = [self.modelManager obtainRequestJSONStringWithOrdertrray:self.goodsArray];
//
}

//赋值总结算金额和抵扣金额,勾选情况
-(void)caculateTotalAmountAndDiscountAmount
{
    CGFloat totalAmount = 0.0f;
    for (MQLFoodModel *model in self.goodsArray) {
        
        totalAmount += (model.price * model.buyCount);
    }
    
    CGFloat disCountAmount = 0.0f;
//    if ([self.sureOrderEntity.couponBalance floatValue] >= [self.sureOrderEntity.ordercouponamount floatValue]) {
//
//        //余额足够的情况下
//        self.disCountAmount = @([self.sureOrderEntity.ordercouponamount floatValue]);
//        self.totalAmount = @([self.sureOrderEntity.ordertotalamount floatValue] - [self.disCountAmount floatValue]);
//
//    }else{
//
//        //余额不足的情况下
        self.disCountAmount = @(disCountAmount);
        self.totalAmount = @(totalAmount);
//    }
}

//检测是否展示限购提示
-(void)checkShowlimitNoticeView
{
    
//    if ([self.sureOrderEntity.promotionType integerValue] == 3) {
//
//        WTOSureOrderGoodsEntity *goods = [self.sureOrderEntity.goods firstObject];
//
//        if([goods.limitNum integerValue] > 0){
//
//        }
//    }
    NSString *noticeMessege = [NSString stringWithFormat:@"每单特价商品仅限购1份，超出1份恢复原价"];
    
    [self.promptView showWithProMessege:noticeMessege];
}

-(void)refreshCellIndentifyArray
{
    [self.goodsCellIndentifyArray removeAllObjects];
    
    for (id object in self.goodsArray) {
        
        [self.goodsCellIndentifyArray addObject:[WTOGoodsCell cellIndentify]];
    }
}

#pragma mark - UITableViewDataSource and Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.goodsCellIndentifyArray.count;
    }else if(section == 1){
        return [self.modelManager getFareDataSourceWithEntity].count;
    }else{
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
                
        MQLFoodModel *entity = self.goodsArray[indexPath.row];
        WTOGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:[WTOGoodsCell cellIndentify] forIndexPath:indexPath];
        [cell updateWithEntityWithGoodsEntity:entity];
        
        return cell;
        
    }else if (indexPath.section == 1){
        
        //正式数据
        NSArray *fareArray = [self.modelManager getFareDataSourceWithEntity];
        WTOpackFareEntity *entity = fareArray[indexPath.row];
        
        WTOOtherExpenseCell *otherExpenCell = [tableView dequeueReusableCellWithIdentifier:[WTOOtherExpenseCell cellIndentify] forIndexPath:indexPath];
        if (!otherExpenCell) {
            
            otherExpenCell = [[WTOOtherExpenseCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[WTOOtherExpenseCell cellIndentify]];
        }
        [otherExpenCell updateWithEntity:entity];
        return otherExpenCell;
        
    }else{
        
        WTOLeaveMessegeCell *cell = [tableView dequeueReusableCellWithIdentifier:[WTOLeaveMessegeCell cellIndentify] forIndexPath:indexPath];
        if (![self.orderObj isInvalidated]) {
            
            cell.invoceTextView.editable = NO;        //必须禁止输入，否则点击将弹出输入键盘
            cell.invoceTextView.text = self.orderObj.remark.length?self.orderObj.remark:@"无留言";
        }
        return cell;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
        WTOSureOrderSectionHeader *sectionHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[WTOSureOrderSectionHeader cellIdentify]];
        if (!sectionHeader) {
            sectionHeader = [[WTOSureOrderSectionHeader alloc]initWithReuseIdentifier:[WTOSureOrderSectionHeader cellIdentify]];
        }
        sectionHeader.backgroundColor = [UIColor whiteColor];
        sectionHeader.delegate = self;
        
        [sectionHeader refreshWithEntity];
        return sectionHeader;
        
    }else{
        return nil;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        
        WTOOrderPayFooterView *footView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[WTOOrderPayFooterView cellIndentify]];
        [footView refreshWithTotalAmount:self.totalAmount];
        return footView;
        
    }else{
        return nil;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        
        return 35;
        
    }else if (indexPath.section == 1){
        
        return 30;
        
    }else{
        
        return 264/2 + 20;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        return 44;
    }else{
        return 0.01;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 44;
    }else{
        return 8;
    }
}

#pragma mark - WTOSureOrderHeaderDelegate
-(void)clickOnorderHeadView:(WTOSureOrderHeadView *)headView
{
    ReceiveGoodsVC *addressVC = [[ReceiveGoodsVC alloc] init];
    addressVC.type = ChooseAddress;

    WS(weakSelf);
    addressVC.settingBack = ^(HDAddressObject *entity){

        self.modelManager.addressObj = entity;
        
        [weakSelf requestData];
    };
    addressVC.editBlock = ^(void){

        [weakSelf requestData];
    };
    addressVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:addressVC animated:YES];
}

#pragma mark - WTOSureOrderSectionHeaderDelegate
-(void)clickSectionHeaderInMessege:(WTOSureOrderSectionHeader *)header
{
    
//    if (self.sureOrderEntity.storeInfo.customlist.count>0) {
//
//        [self showCusotomerServiceList];
//
//    }else
//    {
//        [self contactByWoxinToTalkerId:[NSString stringWithFormat:@"%@",self.sureOrderEntity.storeInfo.storelist.userid] talkerName:self.sureOrderEntity.storeInfo.storelist.name messageKind:MessgeKindSigle mixId:nil];//没有子账号直接跳转IM
//    }

}

//显示客服列表  或者电话列表  不要 回头去掉
- (void)showCusotomerServiceList
{
    
//    UIActionSheet *sheetView = [[UIActionSheet alloc] initWithTitle:@"选择客服"
//                                                           delegate:self
//                                                  cancelButtonTitle:@"取消"
//                                             destructiveButtonTitle:nil
//                                                  otherButtonTitles:nil];
//    for (int i = 0; i < self.sureOrderEntity.storeInfo.customlist.count; i++) {
//
//        WTOCustomListEntity *customEntity = self.sureOrderEntity.storeInfo.customlist[i];
//        [sheetView addButtonWithTitle:customEntity.nickname];
//    }
//
//    if (self.sureOrderEntity.storeInfo.storelist.name && self.sureOrderEntity.storeInfo.storelist.userid) {
//
//        [sheetView addButtonWithTitle:self.sureOrderEntity.storeInfo.storelist.name];
//    }
//
//    [sheetView showInView:self.view];
    
}

-(void)clickSectionHeaderInCall:(WTOSureOrderSectionHeader *)header
{
    HDSellerObject *obj = [HDSellerObject sellerMsg];
    if (!obj.telPhone.length)
    {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:nil message:@"暂无客服电话" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: nil];
        alertView.tag = 999;
        [alertView show];
    }
    else
    {
        WLWShopContactCallView *callView = [[WLWShopContactCallView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, self.view.height) withPhones:@[obj.telPhone]];
        [self.view addSubview:callView];
    }

}

//提交订单
-(void)takeOrder
{
    WTOLeaveMessegeCell *messegeCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    

    if (![self.orderObj isInvalidated] && HDAccount.account.isAdmin && self.orderObj.orderStatus == HDOrderStatusNoVerify) {
        
        //走确认流程
        [[HDBmobFramework sharedInstance] confirmOrderWithObjectId:self.orderObj.objectId complete:^(NSError * _Nullable error) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }else
    {
        [[HDBmobFramework sharedInstance] placeOrderWithFoodList:self.goodsArray amount:self.totalAmount.doubleValue addressObject:self.modelManager.addressObj remark:[messegeCell getLeaveText] complete:^(NSError * _Nullable error) {
            
            for (MQLFoodModel *model in self.modelManager.carArr) {
                model.buyCount = 0;
            }
            [self.modelManager.carArr removeAllObjects];
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }];
    }
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

#pragma mark - UIKeyboardNotification
-(void)keyBoardWillShow:(NSNotification *)notification
{
    NSDictionary *info = notification.userInfo;
    
    CGRect rect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    WTOLeaveMessegeCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    
    CGRect cellRect = [self.view convertRect:cell.frame fromView:self.tableView];
    
    CGFloat cellBottom = cellRect.origin.y + cellRect.size.height;
    
    //如果cell的底部y值大于键盘的顶部，则需要表需要向上便宜
    if (cellBottom > rect.origin.y) {
        
        [UIView animateWithDuration:.2 animations:^{
            
            self.tableView.contentOffset = CGPointMake(0, self.tableView.contentOffset.y + cellBottom - rect.origin.y);
            
        } completion:^(BOOL finished) {
            
        }];
    }
}

-(void)keyBoardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:.2f animations:^{
        
        self.tableView.contentOffset = CGPointZero;
        
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - getter and setter
-(WTOPromptView *)promptView
{
    if (_promptView == nil) {
        
        WTOPromptView *promptView = [[WTOPromptView alloc] init];
        [self.view addSubview:promptView];
        _promptView = promptView;
        
        [_promptView mas_makeConstraints:^(MASConstraintMaker *make) {
           
            make.leading.trailing.mas_equalTo(self.view);
            make.bottom.mas_equalTo(self.view).mas_offset(@-50);
            make.height.mas_equalTo(@34);
            
        }];
    }
    
    return _promptView;
}

-(UITableView *)tableView
{
    if (_tableView == nil) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.contentInset = UIEdgeInsetsMake(8, 0, 0, 0);
        [self.view addSubview:tableView];
        _tableView = tableView;
    }
    
    return _tableView;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
